/**
 * Copyright (C) 2017-2018 pinganfang, Inc. All Rights Reserved.
 */
package com.pingan.haofang.searchcloud.register.route;

import com.google.common.collect.Maps;
import com.pingan.haofang.searchcloud.api.matedata.MetaCacheSupport;
import com.pingan.haofang.searchcloud.api.route.IndexAliasRegister;
import com.pingan.haofang.searchcloud.api.route.IndexRoute;
import com.pingan.haofang.searchcloud.api.route.IndexRouteRegister;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.ApplicationContext;
import org.springframework.jmx.export.annotation.ManagedResource;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * @author huhailiang937
 * @date 2017年7月6日上午11:27:38
 * @since 1.0.0
 */
@Service("zkIndexRouteRegister")
@ManagedResource
@ConditionalOnProperty(name = "seachcloud.meta.zk-host")
public class ZKIndexRouteRegister implements IndexRouteRegister {

    protected static Logger LOG = LoggerFactory.getLogger(ZKIndexRouteRegister.class);

    private static String metaZkHost;

    private static Processor4ZKIndexDiscover discover;

    private static Processor4ZKIndexRegister register;

    // JDK ServiceLoader 初始化需无参构造器
    public ZKIndexRouteRegister() {
        LOG.info("-----> JDK ServiceLoader  IndexRouteRegister for ZKIndexRouteRegister init sucess");
    }

    @Autowired
    public ZKIndexRouteRegister(ApplicationContext applicationContext) {
        metaZkHost = applicationContext.getEnvironment().getProperty(MetaCacheSupport.ZK_CONFIG_KEY);

        LOG.info("---> Route ZK Register Host : " + metaZkHost);

        if (null == metaZkHost) {
            throw new RuntimeException("Property [seachcloud.meta.zk-host] is null");
        }
        Map<String, IndexAliasRegister> map = applicationContext.getBeansOfType(IndexAliasRegister.class);
        map = (null == map) ? Maps.newHashMap() : map;

        register = new Processor4ZKIndexRegister(metaZkHost, map.values());
        discover = new Processor4ZKIndexDiscover(metaZkHost);

        LOG.info("---> Spring loader IndexRouteRegister for  ZKIndexRouteRegister init sucess");
    }

    /*
     * (non-Javadoc)
     * 
     * @see
     * com.pingan.haofang.searchcloud.api.route.IndexRouteRegister#discover(java
     * .lang.String)
     */
    @Override
    public IndexRoute discover(String collectionRouteKey) {
        return discover.discover(collectionRouteKey);
    }

    /*
     * (non-Javadoc)
     * 
     * @see
     * com.pingan.haofang.searchcloud.api.route.IndexRouteRegister#register(com.
     * pingan.haofang.searchcloud.api.route.IndexRoute)
     */
    @Override
    public boolean register(IndexRoute indexRoute) {
        return register.register(indexRoute);
    }

}
